package com.specialtreasure.freightdepot.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.UserUtils;
import com.app.core.fragment.BaseNewFragment;
import com.app.core.view.MarqueeTextView;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.activity.InformationDetailsActivity;
import com.specialtreasure.freightdepot.adapter.GoodsInfoAdapter;
import com.specialtreasure.freightdepot.model.Address;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.ItemBean;
import com.specialtreasure.freightdepot.model.SupplyItems;
import com.specialtreasure.freightdepot.model.SupplyItemsData;
import com.specialtreasure.freightdepot.mq.MQMsg;
import com.specialtreasure.freightdepot.mq.MQUtils;
import com.specialtreasure.freightdepot.popupwindow.SelectCityPW;
import com.specialtreasure.freightdepot.popupwindow.SelectUnitPW;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/21 0021.
 * 货源信息
 */

public class GoodsInfoFragment extends BaseNewFragment implements View.OnClickListener {

    private static final String TAG = "GoodsInfoFragment";
    Integer count = 10;//每页条数
    Integer page = 1;//页数
    String token;
    Boolean hasMode;
    String startProvinceAddress;//出发地(省)
    String startCityAddress;//出发地(市)
    String startCountyAddress;//出发地(县)
    String destProvinceAddress;// 目的地(省)
    String destCityAddress;//目的地(市)
    String destCountyAddress;// 目的地(县)
    String carLength;//车长
    String carType;//车型
    GoodsInfoAdapter goodsInfoAdapter;
    List<ItemBean> itemBeans = new ArrayList<ItemBean>();

    private TextView tv_title;
    private MarqueeTextView tv_navigation;
    private TextView tv_chufadi;
    private RelativeLayout rl_chufadi;
    private TextView tv_mudidi;
    private RelativeLayout rl_mudidi;
    private TextView tv_car_length;
    private RelativeLayout rl_car_length;
    private TextView tv_car_type;
    private RelativeLayout rl_car_type;
    private ListView lv_moto_cade;
    private PtrClassicFrameLayout ptr_layout;
    private LinearLayout ll_root;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(mContext, R.layout.frag_goods_info, null);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 注册对象
        EventBus.getDefault().register(this);
        setData();
        getAD();
    }

    private void setData() {
        tv_title.setText("货源信息");

        //初始化自动刷新
        ptr_layout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_layout.autoRefresh(true);
            }
        }, 150);

        //下拉刷新
        ptr_layout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptr_layout.setLoadMoreEnable(true);
                page = 1;
                itemBeans.clear();
                getData();

            }
        });

        //自动加载更多
        ptr_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!hasMode) {
                    page++;
                    getData();
                } else {
                    Toast.makeText(mContext, "没有更多数据了", Toast.LENGTH_SHORT).show();
                    ptr_layout.setLoadMoreEnable(false);
                }
            }
        });
    }


    private void initView(View view) {
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_navigation = (MarqueeTextView) view.findViewById(R.id.tv_navigation);
        tv_chufadi = (TextView) view.findViewById(R.id.tv_chufadi);
        rl_chufadi = (RelativeLayout) view.findViewById(R.id.rl_chufadi);
        rl_chufadi.setOnClickListener(this);
        tv_mudidi = (TextView) view.findViewById(R.id.tv_mudidi);
        rl_mudidi = (RelativeLayout) view.findViewById(R.id.rl_mudidi);
        rl_mudidi.setOnClickListener(this);
        tv_car_length = (TextView) view.findViewById(R.id.tv_car_length);
        rl_car_length = (RelativeLayout) view.findViewById(R.id.rl_car_length);
        rl_car_length.setOnClickListener(this);
        tv_car_type = (TextView) view.findViewById(R.id.tv_car_type);
        rl_car_type = (RelativeLayout) view.findViewById(R.id.rl_car_type);
        rl_car_type.setOnClickListener(this);
        lv_moto_cade = (ListView) view.findViewById(R.id.lv_moto_cade);
        ptr_layout = (PtrClassicFrameLayout) view.findViewById(R.id.ptr_layout);
        ll_root = (LinearLayout) view.findViewById(R.id.ll_root);

        //跳转到货源详情页
        lv_moto_cade.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (itemBeans != null && itemBeans.size() > 0) {
                    ItemBean itemBean = itemBeans.get(i);
                    intent.putExtra("itemBean", itemBean);
                    intent.setClass(mContext, InformationDetailsActivity.class);
                    startActivity(intent);
                }


            }
        });

    }


    /**
     * 网络请求
     */
    private void getData() {
        token = UserUtils.getToken();
        String url = Constants.HTTP_URL + HttpApi.SUPPLYITEMS;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", token);
        request.add("count", count);
        request.add("page", page);

        request.addNull("startProvinceAddress", startProvinceAddress);
        request.addNull("startCityAddress", startCityAddress);
        request.addNull("startCountyAddress", startCountyAddress);
        request.addNull("destProvinceAddress", destProvinceAddress);
        request.addNull("destCityAddress", destCityAddress);
        request.addNull("destCountyAddress", destCountyAddress);
        request.addNull("carLength", carLength);
        request.addNull("carType", carType);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                ptr_layout.refreshComplete();
                ptr_layout.loadMoreComplete(true);

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                SupplyItems supplyItems = JSON.parseObject(result, SupplyItems.class);

                if (supplyItems != null) {
                    Integer status = supplyItems.getStatus();
                    String msg = supplyItems.getMsg();
                    //判断状态是
                    if (status != null && status == 0) {
                        SupplyItemsData supplyItemsData = supplyItems.getData();
                        if (supplyItemsData != null) {
                            hasMode = supplyItemsData.getHasMore();
                            //适配数据
                            List<ItemBean> itemBeanList = supplyItemsData.getResultList();
                            if (itemBeanList != null && itemBeanList.size() > 0) {
                                ptr_layout.setLoadMoreEnable(true);
                                itemBeans.addAll(itemBeanList);
                            } else {
                                ptr_layout.setLoadMoreEnable(false);
                            }

                            if (goodsInfoAdapter == null) {
                                goodsInfoAdapter = new GoodsInfoAdapter(getActivity());
                                goodsInfoAdapter.setItemBeans(itemBeans);
                                lv_moto_cade.setAdapter(goodsInfoAdapter);
                            } else {
                                goodsInfoAdapter.setItemBeans(itemBeans);
                                goodsInfoAdapter.notifyDataSetChanged();
                            }

                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
    }


    @Override
    protected String getFragmentName() {
        return TAG;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_chufadi://出发地
                SelectCityPW pwTo = new SelectCityPW(getActivity());
                pwTo.showAtBottom(ll_root);
                pwTo.setOnResultListener(new SelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        if (address != null) {
                            startProvinceAddress = address.province;
                            startCityAddress = address.city;
                            startCountyAddress = address.region;
                            tv_chufadi.setText(startProvinceAddress + startCityAddress + startCountyAddress);

                            //城市判断
                            if (startProvinceAddress.equals(startCityAddress)) {
                                startProvinceAddress = "";
                                tv_chufadi.setText(startCityAddress + startCountyAddress);
                            }

                            if (startProvinceAddress.equals("全国")) {
                                startProvinceAddress = "";
                                tv_chufadi.setText("全国");
                            }

                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);

                        }
                    }

                });
                break;
            case R.id.rl_mudidi://目的地
                SelectCityPW pwTo2 = new SelectCityPW(getActivity());
                pwTo2.showAtBottom(ll_root);
                pwTo2.setOnResultListener(new SelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        if (address != null) {
                            destProvinceAddress = address.province;
                            destCityAddress = address.city;
                            destCountyAddress = address.region;
                            tv_mudidi.setText(destProvinceAddress + destCityAddress + destCountyAddress);

                            //城市判断
                            if (destProvinceAddress.equals(destCityAddress)) {
                                destProvinceAddress = "";
                                tv_mudidi.setText(destCityAddress + destCountyAddress);
                            }

                            if (destProvinceAddress.equals("全国")) {
                                destProvinceAddress = "";
                                tv_mudidi.setText("全国");
                            }

                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);

                        }
                    }
                });

                break;
            case R.id.rl_car_length://车长
            case R.id.tv_car_length:
                SelectUnitPW supw = new SelectUnitPW(getActivity(), "chechang.xml", "车长");
                supw.showAtBottom(ll_root);
                supw.setOnResultListener(new SelectUnitPW.OnResultListener() {
                    @Override
                    public void onResult(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            tv_car_length.setText(str);
                            carLength = str;
                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);

                        }
                    }
                });
                break;
            case R.id.rl_car_type://车型
                SelectUnitPW supw1 = new SelectUnitPW(getActivity(), "chexing.xml", "车型");
                supw1.showAtBottom(ll_root);
                supw1.setOnResultListener(new SelectUnitPW.OnResultListener() {
                    @Override
                    public void onResult(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            tv_car_type.setText(str);
                            carType = str;
                            ptr_layout.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ptr_layout.autoRefresh(true);
                                }
                            }, 150);

                        }
                    }
                });
                break;
        }
    }

    /**
     * 获取广告
     */
    private void getAD() {
        String url = Constants.HTTP_URL + HttpApi.ADVERTLIST;
        StringRequest request = new StringRequest(url, RequestMethod.POST);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ONE, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);

                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null) {
                    Integer status = jsonObject.getInteger("status");
                    String msg = jsonObject.getString("msg");

                    if (status != null && status == 0) {
                        List<String> data = JSON.parseArray(jsonObject.getJSONArray("data").toString(), String.class);
                        if (data != null && data.size() > 0) {
                            tv_navigation.init(data);
                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }

                }

            }


        });
    }


    /**
     * 增加条目
     * @param mqMsg
     */
    @Subscriber(tag = Constants.MQ.ANDROIDONE)
    private void addItem(MQMsg mqMsg) {
        if (mqMsg!=null){
//            Logger.e("mqMsg1---"+mqMsg.msg);
            String msg =mqMsg.msg;
            if (!TextUtils.isEmpty(msg)){
               ItemBean itemBean= JSON.parseObject(msg,ItemBean.class);
                if (itemBean!=null){
                    if (goodsInfoAdapter!=null){
                        goodsInfoAdapter.addItem(itemBean);
                    }
                }

            }

        }


    }


    /**
     * 删除条目
     * @param mqMsg
     */
    @Subscriber(tag = Constants.MQ.ANDROIDTWO)
    private void delItem(MQMsg mqMsg) {
//      Logger.e("mqMsg2---"+mqMsg.msg);
        if (mqMsg!=null){
            String msg =mqMsg.msg;
            if (!TextUtils.isEmpty(msg)){
                Integer itemId=Integer.parseInt(msg);
                if (itemId!=null){
                    if (goodsInfoAdapter!=null){
                        goodsInfoAdapter.delItem(itemId);
                    }
                }

            }

        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // 注销
        EventBus.getDefault().unregister(this);
    }

}
